import axios from 'axios'
export default {
  state () {
    return {
      list: []
    }
  },
  mutations: {
    changeList (state, list) {
      state.list = list
    },
    //修改数量
    // updatecount (state, obj) {
    //   let itemobj = state.list.find(item => item.id === obj.id)
    //   itemobj.count = obj.count
    // }

  },
  actions: {
    //获取购物车数据
    async getlist ({ commit }) {
      const res = await axios('http://localhost:3000/cart')
      console.log(res);
      commit('changeList', res.data)
    },

    //修改商品数量
    // async changecount ({ commit }, obj) {
    //   const res = await axios.patch('http://localhost:3000/cart/' + obj.id,
    //     {
    //       count: obj.count
    //     })
    //   commit('updatecount', obj)
    //   console.log(res);
    // }

    async changecount ({ commit }, obj) {
      return new Promise(async (resolve, reject) => {
        const res = await axios.patch('http://localhost:3000/cart/' + obj.id,
          {
            count: obj.count
          })
        resolve(res)
      })
    }







  },
  getters: {
    totle (state) {
      return state.list.reduce((sum, item) => sum + item.count, 0)

    },
    totleprice (state) {
      return state.list.reduce((pre, item) => {
        return pre + item.price * item.count
      }, 0)
    }

  },
  namespaced: true
}